package com.fh.controller.app;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fh.controller.base.BaseController;
import com.fh.entity.system.Role;
import com.fh.entity.system.User;
import com.fh.service.system.appuser.AppuserService;
import com.fh.service.system.role.RoleService;
import com.fh.service.system.user.UserService;
import com.fh.util.AppUtil;
import com.fh.util.Const;
import com.fh.util.DateUtil;
import com.fh.util.MD5;
import com.fh.util.PageData;
import com.fh.util.Tools;
import com.google.gson.JsonObject;


/**
  * app-产品详情-接口类  手机app接口实例
  *    
  * 相关参数协议：
  * 00	操作失败
  * 01	操作成功
  * 02	用户名不存在
  * 03  用户名存在    
  * 04	密码错误
  * 05	请求协议参数不完整    
  * 06  用户名或密码错误
 */
@Controller
@RequestMapping(value="/appKu")
public class AppKuController extends BaseController {
    
//	@Resource(name="appProductService")
//	private AppKuService appProductService;
	
	//@Resource(name="kuService")
	//private KuService kuService;
	
	@Resource(name="appuserService")
	private AppuserService appuserService;
	@Resource(name="roleService")
	private RoleService roleService;
	@Resource(name="userService")
	private UserService userService;
	
	SimpleDateFormat dateFm = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss");
	
	/**
	 * 测试
	 */
	@RequestMapping(value="/test")
	@ResponseBody
	public Object shenqing(){
		List<Map<Object,Object>> list = new ArrayList<Map<Object,Object>>();
		Map<Object,Object> result = new HashMap<Object,Object>();
		logBefore(logger, "测试");
		PageData pd = new PageData();
		Map<Object,Object> map = new HashMap<Object,Object>();
		pd = this.getPageData();
		try {
				for(int i = 0; i < 10; i++)
				{
					result = new HashMap<Object,Object>();
					result.put("PROID","sk0"+String.valueOf(i));
					result.put("PRONAME","name"+String.valueOf(i));
					result.put("USERID","USERID"+String.valueOf(i));
					result.put("USERNAME","USERNAME"+String.valueOf(i));
					result.put("UPLOADTIME",String.valueOf(dateFm.format(new Date())));
					result.put("EDITTMIE",String.valueOf(dateFm.format(new Date())));
					result.put("TYPE","TYPE"+String.valueOf(i));
					result.put("PLAYCOUNTS",5556);
					result.put("DURING",2);
					result.put("DELETESIGN",0);
					result.put("COVER","http://192.168.0.107:8080/THDLOAN/images/test.jpg");
					list.add(result);
				}
				
		} catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", "01");
			map.put("data", list);
			logAfter(logger);
		}
		return AppUtil.returnObject(pd, map);
	}
	
	/**
	 * 访问登录页
	 * @return
	 */
	@RequestMapping(value="/login_toLogin")
	@ResponseBody
	public Object toLogin()throws Exception{
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); //读取系统名称
		Map<Object,Object> map = new HashMap<Object,Object>();
		Map<Object,Object> result = new HashMap<Object,Object>();
		result.put("result", "01");
		result.put("data", map);
		return AppUtil.returnObject(pd, result);
	}
	
	/**
	 * 用户注册
	 * @return
	 */
	@RequestMapping(value="/login_toLogin")
	@ResponseBody
	public Object userReg()throws Exception{
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); //读取系统名称
		Map<Object,Object> map = new HashMap<Object,Object>();
		Map<Object,Object> result = new HashMap<Object,Object>();
		result.put("result", "01");
		result.put("data", map);
		return AppUtil.returnObject(pd, result);
	}
	
	/**
	 * 用户登录
	 * @throws Exception 
	 */
	@RequestMapping(value="/login_login")
	@ResponseBody
	public Object login() throws Exception{
		logBefore(logger, "用户登录");
		PageData pd = new PageData();
		Map<String,Object> map = new HashMap<String,Object>();
		pd = this.getPageData();
		String errInfo = "";
		
		//shiro管理的session
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		
		String USERNAME = pd.get("loginname").toString();
		String PASSWORD  = pd.get("password").toString();
		
		pd.put("USERNAME", USERNAME);
		String passwd = MD5.md5(PASSWORD);	//密码加密
		pd.put("PASSWORD", passwd);
		pd = appuserService.getUserByNameAndPwd(pd);
		if(pd != null){
			pd.put("LAST_LOGIN",DateUtil.getTime().toString());
			appuserService.updateLastLogin(pd);
			User user = new User();
			user.setUSER_ID(pd.getString("USER_ID"));
			user.setUSERNAME(pd.getString("USERNAME"));
			user.setPASSWORD(pd.getString("PASSWORD"));
			user.setNAME(pd.getString("NAME"));
			user.setRIGHTS(pd.getString("RIGHTS"));
			user.setROLE_ID(pd.getString("ROLE_ID"));
			user.setLAST_LOGIN(pd.getString("LAST_LOGIN"));
			user.setIP(pd.getString("IP"));
			user.setSTATUS(pd.getString("STATUS"));
			session.setAttribute(Const.SESSION_USER, user);
			session.removeAttribute(Const.SESSION_SECURITY_CODE);
			
			//shiro加入身份验证
			Subject subject = SecurityUtils.getSubject(); 
		    UsernamePasswordToken token = new UsernamePasswordToken(USERNAME, PASSWORD); 
		    try { 
		        subject.login(token); 
		    } catch (AuthenticationException e) { 
		    	errInfo = "身份验证失败！";
		    }finally{
				logAfter(logger);
			}
		}else{
			errInfo = "用户名或密码有误！";
		}
		if(!"".equals(errInfo)){
			map.put("errInfo", errInfo);
		}else{
			map.put("msg", "success");
			map.put("result", pd);
		}
		return map;
	}
	
	/**
	 * 用户注销
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/logout")
	@ResponseBody
	public Object logout(){
		PageData pd = new PageData();
		//shiro管理的session
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		
		session.removeAttribute(Const.SESSION_USER);
		session.removeAttribute(Const.SESSION_ROLE_RIGHTS);
		session.removeAttribute(Const.SESSION_allmenuList);
		session.removeAttribute(Const.SESSION_menuList);
		session.removeAttribute(Const.SESSION_QX);
		session.removeAttribute(Const.SESSION_userpds);
		session.removeAttribute(Const.SESSION_USERNAME);
		session.removeAttribute(Const.SESSION_USERROL);
		session.removeAttribute("changeMenu");
		
		//shiro销毁登录
		Subject subject = SecurityUtils.getSubject(); 
		subject.logout();
		
		pd = this.getPageData();
		String  msg = "exit";
		pd.put("msg", msg);
		pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); //读取系统名称
		
		return pd;
	}
	
	/**
	 * 访问个人中心
	 * @return
	 */
	@RequestMapping(value="/usercenter")
	public ModelAndView usercenter()throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try{
			//shiro管理的session
			Subject currentUser = SecurityUtils.getSubject();  
			Session session = currentUser.getSession();
			
			User user = (User)session.getAttribute(Const.SESSION_USER);
			if (user != null) {
				pd.put("USERNAME", user.getNAME());
			}
		} catch(Exception e){
			logger.error(e.getMessage(), e);
		}
		
		pd.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); //读取系统名称
		mv.setViewName("thd/usercenter");
		mv.addObject("pd",pd);
		return mv;
	}
	
	/**
	 * 访问我的资料
	 * @return
	 */
	@RequestMapping(value="/myinfo")
	public ModelAndView myinfo()throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try{
			//shiro管理的session
			Subject currentUser = SecurityUtils.getSubject();  
			Session session = currentUser.getSession();
			
			User user = (User)session.getAttribute(Const.SESSION_USER);
			if (user != null) {
				pd.put("USER_ID", user.getUSER_ID());
				pd = appuserService.findUserInfoById(pd);
			}else{
				mv.setViewName("login/index");
				pd.clear();
				mv.addObject("pd",pd);
				return mv;
			}
		} catch(Exception e){
			logger.error(e.getMessage(), e);
		}
		
		mv.setViewName("thd/myinfo");
		mv.addObject("pd",JSONObject.fromObject(pd));
		return mv;
	}
	
	/*
	*//**
	 * 检索列表接口
	 *//*
	@RequestMapping(value="/getList")
	@ResponseBody
	public Object getIntention(){
		String result = "00";
		logBefore(logger, "获取检索列表");
		Map map = new HashMap();
		pd = this.getPageData();
		
		try {
			if (AppUtil.checkParam("FJKEYWORDS", pd)) {
				
				String KEYWORDS = pd.getString("KEYWORDS");
				if(null != KEYWORDS){
					KEYWORDS = KEYWORDS.replaceAll(" ", "").replaceAll("-", "").replaceAll(",", "");
					pd.put("KEYWORDS", KEYWORDS);
				}
				
				int LIMIT = Integer.parseInt(pd.get("LIMIT").toString());
				int oLIMIT = LIMIT + 15;
				pd.put("LIMIT1", LIMIT);
				pd.put("LIMIT2", oLIMIT);
				
				List<PageData> kuList = new ArrayList<PageData>();
				List<PageData> kuListy = kuService.applistkufj(pd);
				
				for(int i=0; i<kuListy.size(); i++){
					
					pd = kuListy.get(i);
					int SQCOUNT = Integer.parseInt(kuService.getSq(pd).get("SQCOUNT").toString());
					pd.put("SQCOUNT", SQCOUNT);
					
					kuList.add(pd);
					
				}
				
				map.put("kuList", kuList);
				map.put("LIMIT", oLIMIT);
				
				result = "01";
				
			}else if(AppUtil.checkParam("KEYWORDS", pd)){//附近搜索
				
				String KEYWORDS = pd.getString("KEYWORDS");
				if(null != KEYWORDS){
					KEYWORDS = KEYWORDS.replaceAll(" ", "").replaceAll("-", "").replaceAll(",", "");
					pd.put("KEYWORDS", KEYWORDS);
				}
				
				int LIMIT = Integer.parseInt(pd.get("LIMIT").toString());
				int oLIMIT = LIMIT + 15;
				pd.put("LIMIT1", LIMIT);
				pd.put("LIMIT2", oLIMIT);
				
				List<PageData> kuList = new ArrayList<PageData>();
				List<PageData> kuListy = kuService.applistku(pd);
				
				for(int i=0; i<kuListy.size(); i++){
					
					pd = kuListy.get(i);
					int SQCOUNT = Integer.parseInt(kuService.getSq(pd).get("SQCOUNT").toString());
					pd.put("SQCOUNT", SQCOUNT);	//商圈数
					
					kuList.add(pd);
					
				}
				
				map.put("kuList", kuList);
				map.put("LIMIT", oLIMIT);
				
				result = "01";
				
			}else {
				result = "05";
			}
		} catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		
		return AppUtil.returnObject(pd, map);
	}
	
	
	
	
	*//**
	 * 检索列表接口(商圈)
	 *//*
	@RequestMapping(value="/getListsq")
	@ResponseBody
	public Object getIntentionsq(){
		String result = "00";
		logBefore(logger, "获取检索列表");
		Map map = new HashMap();
		pd = this.getPageData();
		
		try {
			if (AppUtil.checkParam("FJKEYWORDS", pd)) {
				
				String KEYWORDS = pd.getString("KEYWORDS");
				if(null != KEYWORDS){
					KEYWORDS = KEYWORDS.replaceAll(" ", "").replaceAll("-", "").replaceAll(",", "");
					pd.put("KEYWORDS", KEYWORDS);
				}
				
				int LIMIT = Integer.parseInt(pd.get("LIMIT").toString());
				int oLIMIT = LIMIT + 15;
				pd.put("LIMIT1", LIMIT);
				pd.put("LIMIT2", oLIMIT);
				
				List<PageData> kuList = new ArrayList<PageData>();
				List<PageData> kuListy = kuService.applistkusq(pd);
				
				for(int i=0; i<kuListy.size(); i++){
					
					pd = kuListy.get(i);
					int SQCOUNT = Integer.parseInt(kuService.getSq(pd).get("SQCOUNT").toString());
					pd.put("SQCOUNT", SQCOUNT);
					
					kuList.add(pd);
					
				}
				
				map.put("kuList", kuList);
				map.put("LIMIT", oLIMIT);
				
				result = "01";
				
			}else {
				result = "05";
			}
		} catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		
		return AppUtil.returnObject(pd, map);
	}
	
	
	
	*//**
	 * 同品牌检索列表接口
	 *//*
	@RequestMapping(value="/ppList")
	@ResponseBody
	public Object ppList(){
		String result = "00";
		logBefore(logger, "同品牌获取检索列表");
		Map map = new HashMap();
		pd = this.getPageData();
		
		try {
			if (AppUtil.checkParam("TPP", pd)) {
				
				String PINPAI = pd.getString("PINPAI");
				if(null != PINPAI){
					//PINPAI = PINPAI.replaceAll(" ", "").replaceAll("-", "").replaceAll(",", "");
					pd.put("PINPAI", PINPAI);
				}
				
				int LIMIT = Integer.parseInt(pd.get("LIMIT").toString());
				int oLIMIT = LIMIT + 15;
				pd.put("LIMIT1", LIMIT);
				pd.put("LIMIT2", oLIMIT);
				
				List<PageData> kuList = new ArrayList<PageData>();
				List<PageData> kuListy = kuService.applistpinpai(pd);
				
				for(int i=0; i<kuListy.size(); i++){
					
					pd = kuListy.get(i);
					int SQCOUNT = Integer.parseInt(kuService.getSq(pd).get("SQCOUNT").toString());
					pd.put("SQCOUNT", SQCOUNT);
					
					kuList.add(pd);
					
				}
				
				map.put("kuList", kuList);
				map.put("LIMIT", oLIMIT);
				
				result = "01";
			}else if(AppUtil.checkParam("TPPW", pd)){
				String PINPAI = pd.getString("PINPAI");
				if(null != PINPAI){
					//PINPAI = PINPAI.replaceAll(" ", "").replaceAll("-", "").replaceAll(",", "");
					pd.put("PINPAI", PINPAI);
				}
				
				int LIMIT = Integer.parseInt(pd.get("LIMIT").toString());
				int oLIMIT = LIMIT + 15;
				pd.put("LIMIT1", LIMIT);
				pd.put("LIMIT2", oLIMIT);
				
				List<PageData> kuList = new ArrayList<PageData>();
				List<PageData> kuListy = kuService.applistpinpaiwww(pd);
				
				for(int i=0; i<kuListy.size(); i++){
					
					pd = kuListy.get(i);
					int SQCOUNT = Integer.parseInt(kuService.getSq(pd).get("SQCOUNT").toString());
					pd.put("SQCOUNT", SQCOUNT);
					
					kuList.add(pd);
					
				}
				
				map.put("kuList", kuList);
				map.put("LIMIT", oLIMIT);
				
			}else {
				result = "05";
			}
		} catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		
		return AppUtil.returnObject(pd, map);
	}
	*/
	
}
	
 